package org.example.book.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.book.config.SecurityConfig;
import org.example.book.entity.MyUserDetails;
import org.example.book.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class JwtFilter extends OncePerRequestFilter {

    @Autowired
    UserServiceImpl userServiceImpl;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头
        String authHeader = request.getHeader("Authorization");
        if (StrUtil.isNotBlank(authHeader) && authHeader.startsWith("Bearer ")) {
            // 从请求头中截取 token
            String token = authHeader.substring(7);

            JWT jwt = JWT.of(token).setKey("12345678901234567890".getBytes());

            if (jwt.verify()) { // 判断jwt令牌是否有效
                // 有效则取出userName
                String userName = (String) jwt.getPayload("userName");
                // 根据userName获取用户信息
                UserDetails userDetails = userServiceImpl.loadUserByUsername(userName);
                UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                        = new UsernamePasswordAuthenticationToken(userDetails, null, null);
                // 修改此处，将getAuthentication替换为setAuthentication
                SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            }
        }
        //放行
        filterChain.doFilter(request, response);
    }
}